/**
 * @author Alfred
 * @note 具体定义用户操作的地方，封装sql
 */

package team.wh1tegive.user;

import org.apache.commons.codec.digest.DigestUtils;
import team.wh1tegive.db.DatabaseAction;
import team.wh1tegive.misc.Log;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public abstract class UserAction  {
    protected final String uname;
    protected int uid;

    protected UserAction(String uname) {
        this.uname = uname;
        uid = getUid();
    }

    public String getName() {
        return this.uname;
    }

    protected int getUid() {
        String sql = "SELECT uid FROM User WHERE uname = \"" + uname + "\"";
        try {
            ResultSet rs = DatabaseAction.executeQuery(sql);
            return Integer.parseInt(rs.getString("uid"));
        } catch (SQLException throwables) {
            Log.writeError("Can NOT Get User ID. Check Your User Info.");
            return 0;
        }
    }

    /**
     * @param money 存钱的数额
     * @return 存钱成功返回true，存钱失败返回false
     */
    protected boolean storage(double money) {
        String sql = "UPDATE UserBalanace SET ubalance = ubalance + " + money + " WHERE uid = " + uid + " ;";
        int result = DatabaseAction.executeUpdate(sql);
        if (result == 1) {
            Log.writeLog("User " + uname + " Successfully Storage " + money + " yuan.");
            return true;
        } else {
            Log.writeError("User " + uname + " Storage " + money + " yuan FAILED.");
            return false;
        }
    }

    /**
     * @param money 支出的数额
     * @return 成功支出返回true，余额不足返回false
     */
    protected boolean withdraw(double money) {
        double balance = getBalance();
        String sql = "UPDATE UserBalanace SET ubalance = ubalance - " + money + " WHERE uid = " + uid + " ;";
        int result = DatabaseAction.executeUpdate(sql);
        if (result == 1) {
            Log.writeLog("User " + uname + " Successfully Withdraw " + money + " yuan.");
            if (money >= balance) {
                Log.writeLog("User " + uname + " has Ran Out of Budget.");
            }
            return true;
        } else {
            Log.writeError("User " + uname + " Withdraw " + money + " yuan FAILED.");
            return false;
        }
    }

    public double getBalance() {
        String sql = "SELECT ubalance FROM UserBalance WHERE uid = " + uid + " ;";
        try {
            ResultSet rs = DatabaseAction.executeQuery(sql);
            return Double.parseDouble(rs.getString("ubalance"));
        } catch (SQLException throwables) {
            Log.writeError("Can NOT Get " + uname + "'s Balance.");
        }
        Log.writeError("FATAL ERROR! Application will Restart.");
        System.exit(-1);
        return -1;
    }

    /**
     * @param pwd 要登陆的用户的密码
     * @return 验证成功返回true，验证失败返回false
     */
    public static boolean OauthCheck(String uname, String pwd) {
        // String md5 = DigestUtils.md5Hex(uname + pwd);
        String sql = "SELECT upwd FROM User WHERE uname = \"" + uname + "\";";
        ResultSet rs = DatabaseAction.executeQuery(sql);//rs="upwd"
        try {
            if (rs.next()) {
                String upwd = rs.getString("upwd").strip();
                String token = DigestUtils.md5Hex(uname + pwd);
                rs.close();
                if (upwd.equals(token)) {
                    return true;
                }
            }
        } catch (SQLException e) {
            Log.writeError("Cannot Log In.");
        }
        return false;
    }
    public static boolean aidCheck(String aid){
        String sql = "SELECT * FROM UserAction where aid="+aid+";";
        ResultSet rs = DatabaseAction.executeQuery(sql);
        try {
            if (rs.next()) {
                    return true;
                }
            } catch (SQLException e) {
            Log.writeError("Cannot Log In.");
        }
        return false;

    }
    public  boolean UserActionInsert(CashFlow cashFlow){
        String sql="INSERT INTO UserAction ( uid,aid,date,type,info,amount)\n" +
                "                       VALUES\n" +
                "                       ( 1,\""+cashFlow.actionId+"\",\""+cashFlow.date+"\",\""+cashFlow.isInCome+"\",\""+cashFlow.info+"\","+cashFlow.amount+");";
        int i = DatabaseAction.executeUpdate(sql);
        if(cashFlow.isInCome.equals("收入")){
            UpdateBalance(cashFlow.amount);
        }
        else {
            UpdateBalance(cashFlow.amount*(-1));

        }

        return i == 1;
    }
    public ArrayList<CashFlow> UASelect()  {
        String sql = "select * from UserAction Where uid="+uid+";";
        ArrayList<CashFlow> cfs=new ArrayList<>();
        ResultSet rs = DatabaseAction.executeQuery(sql);
        try {
            while (rs.next()){
              String aid= rs.getString("aid");
              String date= rs.getString("date");
              String type= rs.getString("type");
              String info= rs.getString("info");
              double amount= Double.parseDouble(rs.getString("amount"));
                cfs.add(new CashFlow(aid,date,type,info,amount));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
return cfs;
    }
    public  boolean UserActionUpdate(CashFlow cF){
        String  sql="Update UserAction SET date = \""+cF.date+"\",type=\""+cF.isInCome+"\",info=\""+cF.info+"\",amount="+cF.amount+" where aid="+cF.actionId+";";
        int i = DatabaseAction.executeUpdate(sql);
        if(cF.isInCome.equals("收入")){
            UpdateBalance(cF.amount);
        }
        else {
            UpdateBalance(cF.amount*(-1));

        }
        return i == 1;
    }
    public  boolean UserActionDelete(CashFlow cF){
        String sql="Delete from UserAction where aid=\""+cF.actionId+"\";";
        int i = DatabaseAction.executeUpdate(sql);
        if(cF.isInCome.equals("收入")){
            UpdateBalance(cF.amount);
        }
        else {
            UpdateBalance(cF.amount*(-1));

        }
        return i == 1;
    }
    public ArrayList<CashFlow> UAtypeSelect(String type1)  {
        String sql = "select * from UserAction Where uid= "+uid+" and type="+"\""+type1+"\""+";";
        ArrayList<CashFlow> cfs=new ArrayList<>();
        ResultSet rs = DatabaseAction.executeQuery(sql);
        try {
            while (rs.next()){
                String aid= rs.getString("aid");
                String date= rs.getString("date");
                String type= rs.getString("type");
                String info= rs.getString("info");
                double amount= Double.parseDouble(rs.getString("amount"));
                cfs.add(new CashFlow(aid,date,type,info,amount));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return cfs;
    }

    private  void UpdateBalance(double money){
        String sql="Update UserBalance set ubalance = ubalance +"+money+" where uid ="+uid+";";
        DatabaseAction.executeUpdate(sql);
    }
}

